import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Modal, Form, Input, Flex, Select } from 'antd';
import type { TableProps } from 'antd';
import axios from '../axios/api';
import { useNavigate } from 'react-router-dom';
import type { TableColumnsType } from 'antd';
import type { FormProps } from 'antd';
function Index() {


  const [data, setData] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title, setTitle] = useState('')
  const [title1, setTitle1] = useState('')

  const [id, setId] = useState('')
  const [form] = Form.useForm();

  type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
  const navigate = useNavigate()
  useEffect(() => {
    if (!localStorage.getItem('token')) {
      navigate('/login')
    }
  })

  type FieldType = {
    title?: string;
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }

  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'picture',
      dataIndex: 'picture',
      key: 'picture',
      render: (pictureUrl) => (
        <img
          src={pictureUrl}
          alt="Item"
          style={{ width: 50, height: 'auto', borderRadius: 4 }}
        />
      ),

    },
    {
      title: 'tag',
      dataIndex: 'tag',
      key: 'tag',
    },
    {
      title: 'author',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: 'title',
      dataIndex: 'title',
      key: 'title',
    },

    {
      title: 'update_time',
      dataIndex: 'update_time',
      key: 'update_time',
    },

    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => del(record)}>下架</Button>
          <Button onClick={() => delete1(record)}>删除</Button>
          <Button onClick={() => put(record)}>编辑</Button>
        </Space>
      ),
    },
  ];


  const getData = () => {
    axios.get('/user/getMasterSelfBlog', {
      params: {
        pageNum: 1,
        pageSize: 10,
        title: title1

      }
    }
    ).then((res) => {
      console.log(res);

      const list = res.data.data.filter((item: { publish: number; }) => {
        return item.publish === 0
      })

      setData(list);

    })
  }


  useEffect(() => {
    getData()
  }, [title1])

  const add = () => {
    setTitle('新增')
    setIsModalOpen(true)
    getData()
  }

  const put = (record) => {
    setTitle('编辑')
    setIsModalOpen(true)
    form.setFieldsValue(record);
    setId(record.id)
  }

  // 删除

  const delete1 = (record) => {
    axios.delete('/user/deleteBlog', {
      params: {
        blogId: record.id
      }
    }).then((res) => {
      console.log(res);
      getData()
    })
  }


  // 下架
  const del = (record) => {
    axios.post('/user/updateBlogStatus', {
      blogId: record.id,

      status: 0
    }).then((res) => {
      console.log(res);
      getData()
    })
  }




  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);


    if (title == '新增') {
      axios.post('/user/addBlog', {
        title: values.title,
      }).then((res) => {
        console.log(res);
        getData()
        setIsModalOpen(false)

      })
    } else {
      axios.put('/user/updateBlog', {
        blogId: values.id,
        title: values.title,

        editContent: values.editContent,
        showContent: values.showContent,
        tag: values.tag,
        author: values.author,
      }).then((res) => {
        console.log(res);
        getData()
        setIsModalOpen(false)
      })
    }
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const addMessage = () => {
    axios.post('/user/uploadBlogImage', {
      imagePath: 'https://picsum.photos/200/300?random=2'

    }).then((res) => {
      console.log(res);
      getData()
    })
  }
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);



  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;


  const onFinish1: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    setTitle1(values.title)
  };

  // 清除筛选
  const clearFilter = () => {
    form.resetFields();
    setTitle1('');
  };

  const onFinishFailed1: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Form
          name="filterForm"
          layout="inline"
          onFinish={onFinish1}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="title">
            <Input.Search
              placeholder="按标题筛选"
              allowClear
              onSearch={(value) => setTitle1(value)}
              style={{ width: 300 }}
            />
          </Form.Item>
          <Form.Item>
            <Button onClick={clearFilter}>清除筛选</Button>
          </Form.Item>
        </Form>
      </div>



      <Flex gap="middle" vertical>
        <Flex align="center" gap="middle">

          {hasSelected ? `Selected ${selectedRowKeys.length} items` : null}
        </Flex>
        <Table<DataType> rowSelection={rowSelection} columns={columns} dataSource={data} />


      </Flex>


      <Button onClick={addMessage}> 上传封面</Button>
      <Button onClick={add}>新增</Button>

      <Modal
        title={title}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="id"
            name="id"
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="title"
            name="title"
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="tag"
            name="tag"
          >
            <Select mode="tags" style={{ width: '100%' }} placeholder="请输入标签，按回车添加">
            </Select>
          </Form.Item>
          <Form.Item<FieldType>
            label="editContent"
            name="editContent"
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="showContent"
            name="showContent"
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="author"
            name="author"
          >
            <Input />
          </Form.Item>




          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>

      </Modal>

    </div>
  )
}

export default Index